package cn.edu.zjicm.wordsnet_d.synchronize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import cn.edu.zjicm.wordsnet_d.util.LogUtil;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.caucho.hessian.io.SerializerFactory;

public class HessianSerialization {

	private static final SerializerFactory _serializerFactory = new SerializerFactory();

	public static byte[] serialize2(Object obj) throws IOException {
		long start = System.currentTimeMillis();

		if (obj == null)
			throw new NullPointerException();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		Hessian2Output ho = new Hessian2Output(os);
		ho.setSerializerFactory(_serializerFactory); // 问题所在
		ho.writeObject(obj);
		ho.flush();

		return os.toByteArray();
	}

	public static Object deserialize2(byte[] by) throws IOException {
		long start = System.currentTimeMillis();

		if (by == null)
			throw new NullPointerException();
		ByteArrayInputStream is = new ByteArrayInputStream(by);
		Hessian2Input hi = new Hessian2Input(is);
		hi.setSerializerFactory(_serializerFactory);

		return hi.readObject();
	}

	public static byte[] serialize(Object obj) throws IOException {
		if (obj == null)
			throw new NullPointerException();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		HessianOutput ho = new HessianOutput(os);
		ho.writeObject(obj);
		return os.toByteArray();
	}

	public static Object deserialize(byte[] by) throws IOException {
		if (by == null)
			throw new NullPointerException();

		ByteArrayInputStream is = new ByteArrayInputStream(by);
		HessianInput hi = new HessianInput(is);
		return hi.readObject();
	}
}
